package com.Yukiha.gachamod.Data;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import net.minecraft.network.chat.TextColor;
import net.minecraftforge.fml.loading.FMLPaths;

import javax.annotation.Nullable;
import java.io.IOException;
import java.nio.file.*;
import java.util.*;
import java.util.stream.Stream;

public class ModelInfoManager {

    public static record ModelInfo(
            String id,
            String name,
            String rarity,
            String description,
            @Nullable String iconPath
    ) {}

    private static final Map<String, ModelInfo> MODEL_MAP = new HashMap<>();
    private static final String[] RARITIES = {"common", "rare", "epic", "legendary"};

    /**
     * 加载所有模型信息
     */
    public static void loadFromDisk() {
        MODEL_MAP.clear();

        Path basePath = FMLPaths.CONFIGDIR.get().resolve("yes_steve_model/auth");

        for (String rarity : RARITIES) {
            Path rarityFolder = basePath.resolve(rarity);
            if (!Files.exists(rarityFolder)) continue;

            try (Stream<Path> paths = Files.list(rarityFolder)) {
                for (Path modelDir : paths.toList()) {
                    if (!Files.isDirectory(modelDir)) continue;

                    Path modelJson = modelDir.resolve("ysm.json");
                    if (!Files.exists(modelJson)) continue;

                    try (var reader = Files.newBufferedReader(modelJson)) {
                        JsonObject json = JsonParser.parseReader(reader).getAsJsonObject();

                        String id = modelDir.getFileName().toString();
                        String name = json.has("name") ? json.get("name").getAsString() : id;
                        String description = json.has("description") ? json.get("description").getAsString() : "";
                        String icon = json.has("icon") ? json.get("icon").getAsString() : null;

                        MODEL_MAP.put(id, new ModelInfo(id, name, rarity, description, icon));
                    } catch (Exception e) {
                        System.err.println("[GachaMod] 解析模型失败: " + modelJson);
                        e.printStackTrace();
                    }
                }
            } catch (IOException e) {
                System.err.println("[GachaMod] 加载文件夹失败: " + rarityFolder);
                e.printStackTrace();
            }
        }

        System.out.println("[GachaMod] 模型信息加载完成，共加载 " + MODEL_MAP.size() + " 个模型。");
    }

    /** 热更新（/gacha reload） */
    public static void reload() {
        loadFromDisk();
    }

    public static boolean containsModel(String modelId) {
        return MODEL_MAP.containsKey(modelId);
    }

    public static ModelInfo get(String id) {
        return MODEL_MAP.getOrDefault(id, new ModelInfo(id, id, "common", "", null));
    }

    public static Collection<ModelInfo> getAllModels() {
        return MODEL_MAP.values();
    }

    public static Collection<String> getAllIds() {
        return MODEL_MAP.keySet();
    }

    public static TextColor getColorByRarity(String rarity) {
        return switch (rarity.toLowerCase()) {
            case "legendary" -> TextColor.fromRgb(0xFFD700);
            case "epic"     -> TextColor.fromRgb(0xAA00FF);
            case "rare"     -> TextColor.fromRgb(0x0099FF);
            default         -> TextColor.fromRgb(0xAAAAAA);
        };
    }
}
